from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger

from ctaf_core.ctaf_objects.base_bundle import BaseBundle
from ctaf_core.log_trace_bundle.logging import LogRecorder, LoggerFactory
from ctaf_core.quartz_task_bundle.quartz_scheduler import QuartzSchedulerFactory
from ctaf_core.quartz_task_bundle.quartz_task_data import QuartzTaskData
from ctaf_core.quartz_task_bundle.scheduled_instance_container import ScheduledInstanceContainerFactory


class QuartzTaskBundle(BaseBundle):

    """
    """
    log_recorder: LogRecorder = LoggerFactory.get_logger()

    def __init__(self) -> None:
        super().__init__("QuartzTaskBundle")
        self.quartz_scheduler = QuartzSchedulerFactory.get_quartz_scheduler()

        self.scheduled_instance_container = ScheduledInstanceContainerFactory.get_scheduled_instance_container()

        self.submit_task_from_container()

    def submit_task_from_container(self):
        for quartz_task_name in self.scheduled_instance_container.get_all_quartz_task_names():
            quartz_task_data: QuartzTaskData = self.scheduled_instance_container.get_quartz_task_by_name(quartz_task_name)
            if isinstance(quartz_task_data.task_trigger, CronTrigger):
                self.quartz_scheduler.submit_cron_task(quartz_task_data.task_method_instance, quartz_task_data.task_trigger)
            if isinstance(quartz_task_data.task_trigger, IntervalTrigger):
                self.quartz_scheduler.submit_interval_task(quartz_task_data.task_method_instance, quartz_task_data.task_trigger)

    def load_bundle(self):
        self.quartz_scheduler.start()

    def unload_bundle(self):
        pass